package com.heima.behavior.service.impl;
import java.util.Date;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.mess.UpdateArticleMess;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @作者 itcast
 * @创建日期 2021/4/22 10:35
 **/
@Service
@Slf4j
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    KafkaTemplate kafkaTemplate;


    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        // 1. 校验参数 文章id 注解校验

        // 2. 查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry;
        if(user == null){
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEquipmentId());
        }else {
            behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(),null);
        }
        if(behaviorEntry == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的行为实体数据不存在");
        }
        // 3. 查询阅读行为数据
        ApReadBehavior readBehavior = getOne(Wrappers.<ApReadBehavior>lambdaQuery()
                .eq(ApReadBehavior::getEntryId, behaviorEntry.getId())
                .eq(ApReadBehavior::getArticleId, dto.getArticleId())
        );
        if(readBehavior != null){
            // 3.1 已经存在  修改
            readBehavior.setCount((short)(1 + readBehavior.getCount()));
            readBehavior.setUpdatedTime(new Date());
            updateById(readBehavior);
        }else {
            // 3.2 不存在    新增
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short)1);
            readBehavior.setReadDuration(0);
            readBehavior.setPercentage((short)0);
            readBehavior.setLoadDuration((short)0);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            save(readBehavior);
        }
        // =======================新加代码==========================
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, UUID.randomUUID().toString(), JSON.toJSONString(mess));
        log.info("阅读行为 发送kafka消息 ==>{}",JSON.toJSONString(mess));
        // =======================新加代码==========================
        return ResponseResult.okResult();
    }
}
